package com.sfilyh.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.sfilyh.util.DBUtil;
import com.sfilyh.util.PageBean;
import com.sfilyh.util.StringUtils;

public class ArticleDao {

	/**
	 * 分页搜索文章
	 * @param page
	 * @param pageSize
	 * @param category 分类
	 * @param key    关键字
	 * @param status 状态
	 * @return
	 */
	public PageBean<Map<String,Object>> getAllList(Integer page, Integer pageSize ,Integer category,String key ,Integer[] status){
		
		StringBuffer sb = new StringBuffer();
		List<Object> params = new ArrayList<Object>();
		sb.append("select A.*,B.username,C.cname,DATE_FORMAT(A.createtime,'%Y年%m月%d日') AS ftime from tb_article A ,tb_user B ,tb_category C where A.author = B.id and A.category = C.id ");
				
				 
		if(category != null && category != 0){
			sb.append(" AND A.category = ? ");
			params.add(category);
		}
		
		if(StringUtils.validate(key)){
			sb.append(" AND A.title like ?");
			params.add("'%"+key+"%'");
		}
		
		if(status != null && status.length > 0){
			sb.append(" AND (");
			for(int i = 0 ;i < status.length ;i++){
				sb.append(" A.status = ?");
				params.add(status[i]);
				if(i < status.length -1) sb.append(" OR ");
			}
			sb.append(")");
		}
		
		if(page == null || page == 0) page = 1;			
	    
	    int count = DBUtil.countResutSize(sb.toString(), params.toArray());
	    sb.append("order by A.createtime desc");
	    
	    sb.append(" limit ?,?");
	    params.add((page-1)*pageSize);
	    params.add(pageSize);
	    
	    PageBean<Map<String,Object>> pb = new PageBean<Map<String,Object>>(page,
	    		count,pageSize, DBUtil.queryForListMap(sb.toString(), params.toArray()));
	    
		return pb;
	}
}
